<template>
  <div class="dataEntry">
    <MetaSearchForm @on-search="tableSearch">
      <el-form
        ref="paramsManangement_form"
        :model="searchData"
        label-width="80px"
        class="dataEntry_searchFrom"
      >
        <el-form-item label="设备" class="dataEntry_searchFromItem">
          <el-select
            v-model="searchData.equipmentId"
            placeholder="请选择设备"
            filterable
            clearable
          >
            <el-option
              v-for="item in equipmentList"
              :key="item.value"
              :label="item.equipmentName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检测时间" class="dataEntry_searchFromItem">
          <el-date-picker
            v-model="searchData.dateBetween"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
    </MetaSearchForm>
    <MetaPageTable
      ref="dataEntryTable"
      class="dataEntry_table"
      table-title="录入列表"
      :is-auto-req="false"
      req-method="post"
      :is-manual-paging="true"
      :display-item="displayItem"
      :table-data="dataEntryTableData"
      :btn-group="btnGroup"
      :line-btn-group="lineBtnGroup"
      @btnClick="tableBtnClick"
      @lineBtnClick="tableInlineBtnClick"
      @pageChange="pageChange"
    />
    <el-dialog
      v-if="paramOptionDialogFlag"
      :title="itemEditData.id && itemEditData.id !== '' ? '编辑' : '新建'"
      :visible.sync="paramOptionDialogFlag"
      width="80%"
      modal
      center
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="editDialogClose"
    >
      <el-form
        ref="itemEditData"
        :model="itemEditData"
        label-width="150px"
        :rules="editRules"
        class="newEntry"
      >
        <el-form-item label="录入设备" prop="equipment">
          <el-select
            v-model="itemEditData.equipment"
            filterable
            placeholder="请选择录入设备"
            style="width: 100%"
            @change="changeEq"
          >
            <el-option
              v-for="item in equipmentList"
              :key="item.id"
              :label="item.equipmentName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <div class="inputForm">
          <el-form-item
            :label="item.paramname"
            v-for="(item, index) in paramsList_show"
            :key="index"
            class="inputFormItem"
          >
            <el-input
              v-model="item.paramvalue"
              type="number"
              @input="change($event)"
            ></el-input>
          </el-form-item>
        </div>
        <el-form-item label="检测时间" prop="time">
          <el-select v-model="itemEditData.time" placeholder="请选择" @change="chooseCid" v-if="!isDataNull">
            <el-option
              v-for="item in dateList"
              :key="item.cid"
              :label="item.saveTime"
              :value="item"
            >
            </el-option>
          </el-select>
          <el-date-picker
            v-if="isDataNull"
            v-model="itemEditData.time"
            type="datetime"
            align="right"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div class="dialogFooter">
        <el-button size="mini" @click="editDialogClose()">取消</el-button>
        <el-button type="primary" size="mini" @click="dataDialogSubmit('itemEditData')"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <!-- 导入对话框 -->
    <el-dialog title="数据导入" center 
    v-if="dialogImportVisible"
    :visible.sync="dialogImportVisible" width="width">
      <div>
        <el-form
          ref="itemEditData"
          :model="itemEditData"
          title="数据导入"
          label-width="150px"
          :rules="editRules"
        >
          <el-form-item label="录入设备" prop="equipment">
            <el-select
              v-model="itemEditData.equipment"
              placeholder="请选择录入设备"
              style="width: 100%"
            >
              <el-option
                v-for="item in equipmentList"
                :key="item.id"
                :label="item.equipmentName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文件上传" prop="upload">
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :headers="{
                'x-auth-token': token,
              }"
              :data="importData"
              :limit="1"
              :on-success="uploadSuccess"
              :before-upload="beforeUpload"
            >
              <el-button size="small" type="primary">上传文件并保存</el-button>
              <div slot="tip" class="el-upload__tip">只能上传xlsx或xls格式文件</div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <!-- <div slot="footer">
        <el-button @click="dialogImportVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogImportVisible = false"
          >确 定</el-button
        >
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import MetaPageTable from "../components/MetaPageTable";
import MetaSearchForm from "../components/MetaSearchForm";
import deepClone from "../utils/deepClone";
export default {
  name: "dataEntry",
  components: {
    MetaPageTable,
    MetaSearchForm,
  },
  data() {
    return {
      token: localStorage.getItem("token"),
      uploadUrl: process.env.PROGOO_GATE_WATER + "admin/excel/import",
      paramOptionDialogFlag: false,
      reqUrl: process.env.PROGOO_GATE_WATER + "admin/dataList",
      options: "",
      isDataNull: true,
      itemEditData: {
        id: "",
        equipment: "",
        time: "",
        reflectivityCid: "",
        paramJson: "",
      },
      searchData: {
        equipmentId: "",
        dateBetween: "",
        username: "",
        time: [],
      },
      searchDataForTable: {
        username: "",
      },
      editRules: {
        equipment: [{ required: true, message: "请输入录入设备", trigger: "blur" }],
        params: [{ required: true, message: "请选择录入参数", trigger: "blur" }],
        time: [{ required: true, message: "请输入录入时间", trigger: "blur" }],
      },
      dataEntryTableData: {},
      displayItem: [
        {
          label: "设备",
          prop: "equipmentName",
        },
        {
          label: "检测时间",
          prop: "pickTime",
          width: 160,
        },
        {
          label: "编辑时间",
          prop: "modifyTime",
          width: 160,
        },
      ],
      btnGroup: [
        {
          id: "template",
          title: "模板下载",
        },
        {
          id: "import",
          title: "导入",
        },
        {
          id: "add",
          title: "新建",
        },
      ],
      lineBtnGroup: [
        {
          id: "edit",
          title: "编辑",
        },
        {
          id: "delete",
          title: "删除",
        },
      ],
      equipmentList: [],
      paramsList: [],
      paramsList_show: [],
      tableStyle: {
        fieldName: "status",
        fieldValue: "1",
        backgroundColor: "#ffe3e3",
        fontColor: "",
      },
      params: "",
      ProductActive: "1",
      deleteActive: "",
      dialogImportVisible: false,
      importData: {
        eid: "",
        username: "",
      },
      dateList: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      fileList: [],
    };
  },
  created() {},
  mounted() {
    this.getParams(() => {
      this.initTableData(1, true);
    });
    this.getEquipment();
    this.searchDataForTable.username = localStorage.getItem("username");
    this.searchData.username = localStorage.getItem("username");
  },
  methods: {
    initTableData(page, reflash) {
      let params = {};
      params = this.searchDataForTable;
      params.page = page;
      params.limit = 10;
      params.sortType = "";
      params.sortOrderBy = "";
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/dataList",
        method: "post",
        data: params,
      }).then((res) => {
        if (res.data.code === 200) {
          this.dataEntryTableData = {};
          this.dataEntryTableData.page = page;
          this.dataEntryTableData.totalElements = res.data.result.totalElements;
          this.dataEntryTableData.content = res.data.result.content;
          for (let i in this.dataEntryTableData.content) {
            this.dataEntryTableData.content[i].tempParamJson = JSON.parse(
              this.dataEntryTableData.content[i].paramJson
            );
            for (let key in this.dataEntryTableData.content[i].tempParamJson) {
              this.dataEntryTableData.content[i][key] = this.dataEntryTableData.content[
                i
              ].tempParamJson[key];
            }
          }
          this.$nextTick(() => {
            this.$refs.dataEntryTable.formDataInit(reflash, this.dataEntryTableData);
          });
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    beforeUpload(file) {
      let excelfileExtend = ".xlsx.xls"; //设置文件格式
      let fileExtend = file.name.substring(file.name.lastIndexOf(".")).toLowerCase();
      if (excelfileExtend.indexOf(fileExtend) <= -1) {
        this.$message.error("文件格式错误");
        return;
      }
      this.importData.eid = this.itemEditData.equipment;
      this.importData.username = localStorage.getItem("username");
    },
    uploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.fileList = [];
        this.$notify({
          title: "成功",
          message: "导入成功",
          type: "success",
        });
        this.itemEditData = {};
        this.dialogImportVisible = false;
        this.$nextTick(() => {
          this.initTableData(1, true);
        });
      } else {
        this.fileList = [];
        this.itemEditData = {};

        this.$notify({
          title: "失败",
          message: "导入失败",
          type: "error",
        });
      }
    },
    tableBtnClick(item) {
      if (item.button === "add") {
        this.paramOptionDialogFlag = true;
      } else if (item.button === "template") {
        window.open(process.env.PROGOO_FILE + "data_import.xlsx");
      } else if (item.button === "import") {
        this.dialogImportVisible = true;
      }
    },
    tableInlineBtnClick(item) {
      if (item.button === "edit") {
        this.$fetch({
          url: process.env.PROGOO_GATE_WATER + "admin/content/edit/" + item.rows.id,
          method: "get",
        }).then((res) => {
          if (res.data.code === 200) {
            if(res.data.result != null){
              this.paramOptionDialogFlag = true;
              console.log(res.data.result.reflectivityCid)
              this.itemEditData = {
                id: res.data.result.id,
                equipment: res.data.result.equipmentId,
                time: res.data.result.pickTime,
                reflectivityCid: res.data.result.reflectivityCid
              };
              for (let i in this.paramsList) {
                this.paramsList_show[i] = this.paramsList[i];
                if (item.rows[this.paramsList[i].paramkey] !== null) {
                  for (let j in this.paramsList) {
                    this.itemEditData[this.paramsList[j].paramkey] =
                      item.rows[this.paramsList[j].paramkey];
                    this.paramsList_show[j].paramvalue = item.rows[this.paramsList[j].paramkey];
                  }
                }
              }
            }
          } else {
            this.$notify.error({
              title: "错误",
              message: res.data.result,
            });
          }
        });
        
        
      } else if (item.button === "delete") {
        this.$confirm("确认删除本条数据？数据删除后无法找回", "确认删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "delete/data/" + item.rows.id,
            method: "delete",
          }).then((res) => {
            if (res.data.code === 200) {
              this.$notify.success({
                title: "成功",
                message: "已成功删除本条数据",
              });
              this.$nextTick(() => {
                this.initTableData(1, true);
              });
            } else {
              this.$notify.error({
                title: "错误",
                message: res.data.result,
              });
            }
          });
        });
      }
    },
    tableSearch() {
      let param = {};
      for (let key in this.searchData) {
        if (key === "dateBetween") {
          param.dateStart =
            this.searchData[key] && this.searchData[key].length > 0
              ? this.searchData[key][0]
              : "";
          param.dateEnd =
            this.searchData[key] && this.searchData[key].length > 0
              ? this.searchData[key][1]
              : "";
          this.searchData.time = [];
          this.searchData.time[0] = param.dateStart;
          this.searchData.time[1] = param.dateEnd;
        } else {
          param[key] = this.searchData[key];
        }
      }
      this.searchDataForTable = param;
      this.$nextTick(() => {
        this.initTableData(1, true);
      });
    },
    pageChange(e) {
      this.initTableData(e, false);
    },
    editDialogClose() {
      for (let i in this.paramsList_show) {
        this.paramsList_show[i].paramvalue = "";
      }
      this.itemEditData = {};
      this.dateList = []
      this.paramOptionDialogFlag = false;
    },
    change(e) {
      //强制刷新组件
      this.$forceUpdate();
    },
    changeEq(value) {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "reflectivity/time",
        method: "post",
        data: { equipmentId: value },
      }).then((res) => {
        if (res.data.code == 200) {
          if(res.data.result.length !== 0){
            this.dateList = res.data.result;
            this.isDataNull = false
          }else{
            this.isDataNull = true
          }
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    chooseCid(value) {
      console.log(value)
      this.itemEditData.reflectivityCid = value.cid;
      this.itemEditData.time = value.saveTime;
    },
    dataDialogSubmit(formName) {
      let username = localStorage.getItem("username");
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {};
          params.id = this.itemEditData.id;
          params.username = username;
          params.equipmentId = this.itemEditData.equipment;
          params.pickTime = this.itemEditData.time;
          params.reflectivityCid = this.itemEditData.reflectivityCid;
          let tempParam = {};
          for (let i in this.paramsList) {
            if (!this.paramsList_show[i].paramvalue) {
              this.paramsList_show[i].paramvalue = "";
            }
            tempParam[this.paramsList[i].paramkey] = this.paramsList_show[i].paramvalue;
          }
          let temp = JSON.stringify(tempParam);
          params.paramJson = temp;
          this.$fetch({
            url: process.env.PROGOO_GATE_WATER + "admin/content/input",
            method: "post",
            data: params,
          }).then((res) => {
            if (res.data.code === 200) {
              if(res.data.result == '数据重复'){
                this.$notify.error({
                title: "数据重复",
                message: '请修改检测时间',
              });
              }else{
                  this.$notify.success({
                    title: "上传成功",
                    message: res.data.message,
                  });
                  this.paramOptionDialogFlag = false;
                  this.$nextTick(() => {
                    this.initTableData(1, true);
                    this.itemEditData = {};
                    for (let i in this.paramsList_show) {
                      this.paramsList_show[i].paramvalue = "";
                    }
                    this.dateList = []
                    // this.paramsList = [];
                  });
              }
            } else {
              this.$notify.error({
                title: "错误",
                message: res.data.message,
              });
            }
          });
        } else {
          this.$notify.error({
            title: "错误",
            message: "请选择设备/参数/时间",
          });
        }
      });
    },
    getEquipment() {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/algorithm/equipmentList",
        method: "get",
        data: {},
      }).then((res) => {
        if (res.data.code === 200) {
          this.equipmentList = res.data.result;
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
    getParams(callback) {
      this.$fetch({
        url: process.env.PROGOO_GATE_WATER + "admin/paramThreshold",
        method: "post",
        data: {
          page: 1,
          limit: 999,
        },
      }).then((res) => {
        if (res.data.code === 200) {
          this.paramsList = res.data.result.content;
          this.paramsList.reverse();
          this.paramsList_show = deepClone(this.paramsList);

          for (let i in this.paramsList) {
            this.displayItem.push(this.paramsList[i]);
          }
          for (let j = 3; j < this.displayItem.length; j++) {
            this.displayItem[j].prop = this.displayItem[j].paramkey;
            this.displayItem[j].width = "80px";
            this.displayItem[j].label = this.displayItem[j].paramname;
          }

          // this.$nextTick(() => {
          //   this.$refs.dataEntryTable.formDataInit(reflash, this.dataEntryTableData);
          // });
          if (callback && typeof callback === "function") {
            callback();
          }
        } else {
          this.$notify.error({
            title: "错误",
            message: res.data.message,
          });
        }
      });
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.dataEntry {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 15px;
  overflow-y: scroll;
  .dataEntry_table {
    width: 100%;
    overflow-y: unset;
  }
  .dataEntry_searchFrom {
    width: 100%;
  }
  .dataEntry_searchFromItem {
    float: left;
  }
  .dialogFooter {
    display: flex;
    justify-content: center;
    margin-top: 0.5rem;
  }
  .newEntry {
    width: 100%;
    .inputForm {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      .inputFormItem {
        width: 25%;
      }
    }
  }
}
</style>
